package com.lgz.dbcourse.gui;

import com.lgz.dbcourse.dto.*;
import com.lgz.dbcourse.service.StaffService;
import com.lgz.dbcourse.service.impl.StaffServiceImpl;


import javax.swing.*;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;

import java.awt.*;
import java.awt.event.*;
import java.lang.reflect.Method;

/**
 * @Author: LGZ
 * @Date: 2021/4/13 18:55
 * @Description:
 */
public class ManagePanel extends JPanel{

    private JFrame jFrame;
    private StaffOutputDTO staffOutputDTO;
    private ScheduleDTO[] scheduleDTOs;
    private StaffService staffService;
    private ManagePanel managePanel;
    private JPanel scheduleJpanel;

    public ManagePanel(JFrame jf, StaffOutputDTO staffOutput) {
        managePanel = this;
        jFrame = jf;
        staffOutputDTO = staffOutput;
        staffService = new StaffServiceImpl();
        this.setLayout(null);
        this.setSize(980, 600);
        createBack();
        createStaffInfo();
        createSchedulePanel();

    }


    /**
     * TODO
     * @Description 个人信息面板
     * @Author lgz
     * @Date 2021/4/15 20:46
     */
    public void createStaffInfo() {
        JPanel staff = new JPanel();
        staff.setBorder(BorderFactory.createTitledBorder("个人信息"));
        staff.setBounds(720, 80, 200, 180);
        staff.setLayout(new GridLayout(3, 2));
        staff.setBackground(Color.WHITE);
        JLabel staffIdLabel = new JLabel("工号");
        staffIdLabel.setBounds(30, 30, 100, 30);
        staff.add(staffIdLabel);
        JLabel staffId = new JLabel(staffOutputDTO.getStaffId().toString());
        staffId.setBounds(130, 30, 100, 30);
        staff.add(staffId);
        JLabel staffUsernameLabel = new JLabel("账号");
        staffUsernameLabel.setBounds(30, 70, 100, 30);
        staff.add(staffUsernameLabel);
        JLabel staffUsername = new JLabel(staffOutputDTO.getUsername());
        staffUsername.setBounds(130, 70, 100, 30);
        staff.add(staffUsername);
        JLabel staffNameLabel = new JLabel("姓名");
        staffNameLabel.setBounds(30, 110, 100, 30);
        staff.add(staffNameLabel);
        JLabel staffName = new JLabel(staffOutputDTO.getStaffName());
        staffName.setBounds(130, 110, 100, 30);
        staff.add(staffName);
        this.add(staff);
    }

    public void createSchedulePanel() {
        JPanel jPanel = new JPanel(null);
        scheduleJpanel = jPanel;
        jPanel.setBounds(60, 100, 560, 300);

        // 标签
        MyLabel label1 = new MyLabel("影片名");
        MyLabel label2 = new MyLabel("影厅");
        MyLabel label3 = new MyLabel("开始时间");
        label1.setBounds(10, 0, 50, 30);
        label2.setBounds(120, 0, 50, 30);
        label3.setBounds(250, 0, 50, 30);
        jPanel.add(label1);
        jPanel.add(label2);
        jPanel.add(label3);

        // 排片信息列表
        scheduleDTOs = (ScheduleDTO[])staffService.getSchedule().getData();
        String[] schedules = new String[scheduleDTOs.length];
        for (int i = 0; i < scheduleDTOs.length; i++) {
            schedules[i] = scheduleDTOs[i].toString();
        }
        JList<String> schedule = new JList<>(schedules);
        schedule.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        schedule.setSize(350, 50);
        schedule.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (2 == e.getClickCount()) {
                    MovieDTO movieDTO = new MovieDTO();
                    movieDTO.setMovieId(scheduleDTOs[schedule.getLeadSelectionIndex()].getMovieId());
                    JLabel jLabel = new JLabel(((MovieDTO)staffService.getMovie(movieDTO).getData()).toDialog());
                    jLabel.setHorizontalAlignment(JLabel.CENTER);
                    JDialog jDialog = new JDialog(jFrame, "info");
                    jDialog.setSize(400, 300);
                    jDialog.add(jLabel);
                    jDialog.setResizable(false);
                    jDialog.setLocationRelativeTo(jFrame);
                    jDialog.setModal(true);
                    jDialog.setVisible(true);
                    jDialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
                }
            }
        });

        // 滚动框
        JScrollPane jScrollPane = new JScrollPane();
        jScrollPane.setBackground(Color.white);
        jScrollPane.setBounds(0, 30, 560, 200);
        jScrollPane.setViewportView(schedule);
        jPanel.add(jScrollPane);


        // 按钮
        JButton newMovie = new JButton("新建影片");
        newMovie.setActionCommand("NewMovie");
        newMovie.setBounds(10, 240, 100, 40);
        jPanel.add(newMovie);
        newMovie.addActionListener(e -> {

            JDialog jDialog = new JDialog(jFrame, "新建影片");
            jDialog.setSize(500, 300);
            jDialog.setBackground(Color.LIGHT_GRAY);
            jDialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
            JPanel jPanel1 = new JPanel(null);
            jPanel1.setBounds(0, 0, 500, 300);

            MyLabel movieNameLabel = new MyLabel("影片名");
            movieNameLabel.setBounds(0, 10, 120, 40);
            JTextField movieName = new JTextField();
            movieName.setBounds(130, 10, 250, 40);
            jPanel1.add(movieNameLabel);
            jPanel1.add(movieName);

            MyLabel movieDirectorLabel = new MyLabel("导演");
            movieDirectorLabel.setBounds(0, 60, 120, 40);
            JTextField movieDirector = new JTextField();
            movieDirector.setBounds(130, 60, 250, 40);
            jPanel1.add(movieDirectorLabel);
            jPanel1.add(movieDirector);

            MyLabel mainActorLabel = new MyLabel("主演");
            mainActorLabel.setBounds(0, 110, 120, 40);
            JTextField mainActor = new JTextField();
            mainActor.setBounds(130, 110, 250, 40);
            jPanel1.add(mainActorLabel);
            jPanel1.add(mainActor);

            MyLabel movieDurationLabel = new MyLabel("时长");
            movieDurationLabel.setBounds(0, 160, 120, 40);
            JTextField movieDuration = new JTextField();
            movieDuration.setBounds(130, 160, 250, 40);
            jPanel1.add(movieDurationLabel);
            jPanel1.add(movieDuration);

            MyLabel movieDistrictLabel = new MyLabel("地区");
            movieDistrictLabel.setBounds(0, 210, 120, 40);
            JTextField movieDistrict = new JTextField();
            movieDistrict.setBounds(130, 210, 250, 40);
            jPanel1.add(movieDistrictLabel);
            jPanel1.add(movieDistrict);

            JButton submit = new JButton("提交");
            submit.setActionCommand("Submit");
            submit.setBounds(400, 110, 60, 40);
            jPanel1.add(submit);
            submit.addActionListener((event)->{
                JDialog jDialog1 = new JDialog(jFrame, "info");
                jDialog1.setSize(200, 100);
                MyLabel myLabel;
                jDialog1.setResizable(false);
                jDialog1.setLocationRelativeTo(jFrame);
                jDialog1.setModal(true);
                if (movieName.getText().length() == 0 || movieDirector.getText().length() == 0 || movieDistrict.getText().length() == 0 || movieDuration.getText().length() == 0 || mainActor.getText().length() == 0) {
                    myLabel = new MyLabel("请输入完整信息");
                    jDialog1.add(myLabel);
                    jDialog1.setVisible(true);
                } else {
                    MovieDTO movieDTO1 = new MovieDTO();
                    movieDTO1.setMainActor(mainActor.getText());
                    movieDTO1.setMovieDuration(movieDuration.getText());
                    movieDTO1.setMovieDirector(movieDirector.getText());
                    movieDTO1.setMovieName(movieName.getText());
                    movieDTO1.setMovieDistrict(movieDistrict.getText());
                    myLabel = new MyLabel(staffService.addMovie(movieDTO1).getMsg());
                    jDialog1.add(myLabel);
                    jDialog1.setVisible(true);
                    jDialog1.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
                    jDialog.dispose();

                }
            });

            jDialog.add(jPanel1);
            jDialog.setResizable(false);
            jDialog.setLocationRelativeTo(jFrame);
            jDialog.setModal(true);
            jDialog.setVisible(true);
        });

        JButton newSchedule = new JButton("排片");
        newSchedule.setActionCommand("NewSchedule");
        newSchedule.setBounds(150, 240, 100, 40);
        newSchedule.addActionListener(e -> {
            JDialog jDialog = new JDialog(jFrame, "选择影片");
            jDialog.setSize(500, 300);
            jDialog.setBackground(Color.WHITE);jDialog.setResizable(false);
            jDialog.setLocationRelativeTo(jFrame);
            jDialog.setModal(true);
            jDialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
            MovieDTO[] movieDTOs = (MovieDTO[])staffService.getAllMovie().getData();
            final JTable table = getMovieTableNotEditable(movieDTOs);
            JScrollPane jScrollPane1 = new JScrollPane(table);
            jScrollPane1.setBounds(0, 0, 500, 200);
            JPanel jPanel1 = new JPanel(null);
            jPanel1.setBounds(0, 0, 500, 300);
            jPanel1.add(jScrollPane1);
            JButton jButton = new JButton("确定");
            jButton.setBounds(210, 200, 80, 40);
            jPanel1.add(jButton);


            jButton.addActionListener(e12 -> {
                // 确定电影Id
                MovieScheduleDTO movieScheduleDTO = new MovieScheduleDTO();
                try {
                    movieScheduleDTO.setMovieId(movieDTOs[table.getSelectedRow()].getMovieId());
                } catch (ArrayIndexOutOfBoundsException ee) {
                    return;
                }
                jScrollPane1.remove(table);
                HallDTO[] hallDTOs = (HallDTO[])staffService.getAllHall().getData();
                JTable table1 = getHallTable(hallDTOs);
                jScrollPane1.add(table1);
                jScrollPane1.setViewportView(table1);
                jPanel1.remove(jButton);
                JButton jButton1 = new JButton("确定");
                jButton1.setBounds(210, 200, 80, 40);
                jPanel1.add(jButton1);
                jButton1.addActionListener(e13 -> {
                    try {
                        movieScheduleDTO.setHallId(hallDTOs[table1.getSelectedRow()].getHallId());
                    } catch (ArrayIndexOutOfBoundsException eee) {
                        return;
                    }
                    jPanel1.remove(jScrollPane1);
                    jPanel1.remove(jButton1);
                    DateChooserJButton dateChooserJButton = new DateChooserJButton();
                    dateChooserJButton.setBounds(0, 0, 300, 200);
                    jDialog.dispose();
                    MyFrame mainFrame = new MyFrame("选择时间");
                    mainFrame.setSize( 300 , 300 );
                    mainFrame.add(dateChooserJButton);
                    mainFrame.setVisible(true);
                    mainFrame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
                    mainFrame.setLocationRelativeTo(null);
                    mainFrame.addWindowListener(new WindowAdapter() {
                        @Override
                        public void windowClosing(WindowEvent e) {
                            JLabel jLabel;
                            if (dateChooserJButton.getChoose()) {
                                movieScheduleDTO.setStartTime(dateChooserJButton.getDate());
                                staffService.addSchedule(movieScheduleDTO);
                                jLabel = new JLabel("创建成功");
                            } else {
                                jLabel = new JLabel("创建失败");
                            }
                            jLabel.setHorizontalAlignment(JLabel.CENTER);
                            JDialog jDialog = new JDialog(jFrame, "Msg");
                            jDialog.setSize(200, 100);
                            jDialog.add(jLabel);
                            jDialog.setResizable(false);
                            jDialog.setLocationRelativeTo(jFrame);
                            jDialog.setModal(true);
                            jDialog.setVisible(true);
                            managePanel.remove(scheduleJpanel);
                            createSchedulePanel();
                            jFrame.repaint();
                            jFrame.validate();
                        }
                    });
                });


//                jPanel1.remove(jScrollPane1);
                jDialog.repaint();
                jDialog.validate();
            });

            jDialog.add(jPanel1);
            jDialog.setVisible(true);
        });

        JButton showMovie = new JButton("所有影片");
        showMovie.setActionCommand("ShowMovie");
        showMovie.setBounds(290, 240, 100, 40);
        showMovie.addActionListener(e -> {
            JDialog jDialog = new JDialog(jFrame, "所有影片, 双击直接修改");
            jDialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
            jDialog.setSize(500, 300);
            jDialog.setBackground(Color.WHITE);jDialog.setResizable(false);
            jDialog.setLocationRelativeTo(jFrame);
            jDialog.setModal(true);

            MovieDTO[] movieDTOs = (MovieDTO[])staffService.getAllMovie().getData();
//                String[] movieDTOStr = new String[movieDTOS.length];
//                for (int i = 0; i < movieDTOS.length; i++) {
//                    movieDTOStr[i] = movieDTOS[i].toList();
//                }
//                JList<String> stringJList = new JList<>(movieDTOStr);
//                stringJList.setBounds(0, 0, 500, 300);

//                JScrollPane js = new JScrollPane(stringJList);
//                jDialog.add(js);

            String[] method = {"setMovieName", "setMovieDirector", "setMainActor", "setMovieDuration", "setMovieDistrict"};

            JTable table = getMovieTable(movieDTOs);
            table.setBounds(0,  0, 480, 250);
            JScrollPane jScrollPane1 = new JScrollPane(table);
            jScrollPane1.setBounds(0, 0, 480, 250);

            table.getModel().addTableModelListener(e1 -> {
                // 获取修改的行下标
                int row = e1.getFirstRow();
                // 获取修改的列
                int column = e1.getColumn();
                try {
                    Method set = MovieDTO.class.getDeclaredMethod(method[column], String.class);
                    set.invoke(movieDTOs[row], table.getValueAt(row, column).toString());
                    staffService.updateMovie(movieDTOs[row]);
                } catch (Exception er) {
                    er.printStackTrace();
                }
            });

            jDialog.add(jScrollPane1);

            jDialog.setVisible(true);
        });

        jPanel.add(newSchedule);
        jPanel.add(showMovie);


        this.add(jPanel);

    }

    public void createBack() {
        JButton back = new JButton("返回");
        back.setActionCommand("Back");
        back.setBounds(10, 10, 70, 30);
        back.addActionListener((e)->{
            // 返回主界面
            jFrame.dispose();
            new MainFrame().start();
        });
        this.add(back);
    }

    private DefaultTableModel getTableModel(MovieDTO[] movieDTOs) {
        String[] columnNames = {"影片名", "导演", "主演", "时长", "地区"};
        String[][] tableValues = new String[movieDTOs.length][5];
        for (int i = 0; i < movieDTOs.length; i++) {
            tableValues[i][0] = movieDTOs[i].getMovieName();
            tableValues[i][1] = movieDTOs[i].getMovieDirector();
            tableValues[i][2] = movieDTOs[i].getMainActor();
            tableValues[i][3] = movieDTOs[i].getMovieDuration();
            tableValues[i][4] = movieDTOs[i].getMovieDistrict();
        }
        return new DefaultTableModel(tableValues, columnNames);
    }

    private JTable getHallTable(HallDTO[] hallDTOs) {
        String[] columnNames = {"影厅编号", "影厅名"};
        String[][] tableValues = new String[hallDTOs.length][2];
        for (int i = 0; i < hallDTOs.length; i++) {
            tableValues[i][0] = hallDTOs[i].getHallId().toString();
            tableValues[i][1] = hallDTOs[i].getHallName();
        }


        JTable table = new JTable(new DefaultTableModel(tableValues, columnNames)) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };

        DefaultTableCellRenderer tcr = new DefaultTableCellRenderer();
        tcr.setHorizontalAlignment(JLabel.CENTER);
        table.setDefaultRenderer(Object.class, tcr);
        table.setBounds(0,  0, 480, 250);
        table.getTableHeader().setDefaultRenderer(tcr);
        table.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
        return table;
    }

    private JTable getMovieTable(MovieDTO[] movieDTOs) {
        JTable table = new JTable(getTableModel(movieDTOs));
        table.setBounds(0,  0, 480, 250);
        return table;
    }

    private JTable getMovieTableNotEditable(MovieDTO[] movieDTOs) {
        JTable table = new JTable(getTableModel(movieDTOs)) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        table.setBounds(0,  0, 480, 250);
        table.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
        return table;
    }


}
